<template>
  <el-dialog
    center
    :title="type == 'add' ? '添加' : '编辑'"
    v-model="Visible"
    width="35%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="dialogForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="热源名称" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="热源编码" prop="code">
        <el-input v-model="ruleForm.code"></el-input>
      </el-form-item>
      <el-form-item label="热源别名" prop="shortName">
        <el-input v-model="ruleForm.shortName"></el-input>
      </el-form-item>
      <el-form-item label="经度" prop="longitude">
        <el-input v-model="ruleForm.longitude" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="纬度" prop="latitude">
        <el-input v-model="ruleForm.latitude" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="标签" prop="label">
        <el-tag
          :key="index"
          v-for="(tag, index) in ruleForm.label"
          closable
          style="margin-right: 10px"
          :disable-transitions="false"
          @close="handleTagClose(tag, index)"
        >
          {{ tag }}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          style="width: 100px"
          @keyup.enter="handleInputConfirm"
          @blur="handleInputConfirm"
        >
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="AddTags"
          >+ 添加</el-button
        >
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          type="textarea"
          v-model="ruleForm.remark"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input
          v-model="ruleForm.sort"
          onkeyup="value=value.replace(/[^\d]/g,'')"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          v-preventReClick
          @click="submitForm('ruleForm')"
          >确定</el-button
        >
        <el-button @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
import { reactive, toRefs, ref, onMounted, nextTick } from "vue";
import { addHeatSource, editHeatSource } from "@/api/heatSource";
import { ElMessage } from "element-plus";
export default {
  name: "UpdatePassword",
  props: {
    Visible: {
      type: Boolean,
      default: false,
    },
    dialogRow: {
      type: Object,
      default: {},
    },
    type: {
      type: String,
      default: "add",
    },
  },
  setup(props, context) {
    const saveTagInput = ref(null);
    const dialogForm = ref(null);
    const validateLong = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入经度值"));
      } else if (!/^[0-9.]*$/.test(value)) {
        callback(new Error("请输入数字类型的值"));
      } else {
        callback();
      }
    };
    const validateLat = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入纬度值"));
      } else if (!/^[0-9.]*$/.test(value)) {
        callback(new Error("请输入数字类型的值"));
      } else {
        callback();
      }
    };

    const state = reactive({
      inputVisible: false,
      inputValue: "",
      ruleForm: {
        name: "",
        code: "",
        shortName: "",
        longitude: 0,
        latitude: 0,
        label: [],
        sort: 100,
        remark: "",
      },
      rules: {
        name: [{ required: true, message: "请输入热源名称", trigger: "blur" }],
        shortNam: [{ required: true, message: "请输入别名", trigger: "blur" }],
        code: [{ required: true, message: "请输入热源编码", trigger: "blur" }],
        longitude: [
          {
            required: true,
            validator: validateLong,
            trigger: "blur",
          },
        ],
        latitude: [
          {
            required: true,
            validator: validateLat,
            trigger: "change",
          },
        ],
      },
    });

    const AddTags = () => {
      state.inputVisible = true;
    };
    const handleTagClose = (tag, index) => {
      state.ruleForm.label.splice(index, 1);
    };
    const handleInputConfirm = () => {
      let inputValue = state.inputValue;
      if (state.ruleForm.label.includes(inputValue)) {
        return ElMessage.error("标签已重复，请重新填写");
      }
      if (inputValue) {
        state.ruleForm.label.push(inputValue);
      }
      state.inputVisible = false;
      state.inputValue = "";
    };

    onMounted(() => {
      if (props.type == "add") {
        nextTick(() => {
          dialogForm.value.resetFields();
        });
      } else {
        state.ruleForm = props.dialogRow;
        // state.ruleForm.label=JSON.parse(label)
      }
    });
    const submitForm = () => {
      dialogForm.value.validate((valid) => {
        if (valid) {
          const {
            name,
            code,
            shortName,
            longitude,
            latitude,
            label,
            sort,
            remark,
          } = state.ruleForm;
          let params = {
            name,
            code,
            shortName,
            longitude,
            latitude,
            label: label.join(","),
            sort,
            remark,
          };

          if (props.type == "add") {
            addHeatSource(params).then((res) => {
              if (res.data.success) {
                ElMessage.success(res.data.msg);
                handleClose();
                context.emit("refresh");
              }
            });
          } else {
            params.id = state.ruleForm.id;
            editHeatSource(params).then((res) => {
              if (res.data.success) {
                ElMessage.success(res.data.msg);
                handleClose();
                context.emit("refresh");
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    };

    const handleClose = () => {
      context.emit("close", false);
    };

    return {
      ...toRefs(state),
      saveTagInput,
      AddTags,
      submitForm,
      dialogForm,
      handleClose,
      handleInputConfirm,
      handleTagClose,
    };
  },
};
</script>
